package com.easylinkin.linkappapi.circuit.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.easylinkin.linkappapi.circuit.dto.*;
import com.easylinkin.linkappapi.circuit.entity.RailCircuitGivealarm;
import com.easylinkin.linkappapi.circuit.mapper.RailCircuitGivealarmMapper;
import com.easylinkin.linkappapi.circuit.service.IRailCircuitGivealarmService;
import com.easylinkin.linkappapi.circuit.service.IRailGiveSystemAlarmService;
import com.easylinkin.linkappapi.circuit.vo.RailCircuitGivealarmVO;
import com.easylinkin.linkappapi.common.utils.DateUtil;
import com.easylinkin.linkappapi.config.dao.SysDictItemMapper;
import com.easylinkin.linkappapi.config.dao.SysDictMapper;
import com.easylinkin.linkappapi.config.entity.SysDict;
import com.easylinkin.linkappapi.config.entity.SysDictItem;
import com.easylinkin.linkappapi.config.service.SysDictItemService;
import com.easylinkin.linkappapi.device.constant.DeviceConstant;
import com.easylinkin.linkappapi.device.entity.Device;
import com.easylinkin.linkappapi.device.mapper.DeviceMapper;
import com.easylinkin.linkappapi.device.service.DeviceService;
import com.easylinkin.linkappapi.openapi.dto.DatapushDTO;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.util.*;

/**
 * 报警/故障记录服务类
 * @author lyk
 * @date 2025/6/16 下午 2:38
 */
@Service
@Slf4j
public class RailCircuitGivealarmServiceImpl  extends ServiceImpl<RailCircuitGivealarmMapper, RailCircuitGivealarm>  implements IRailCircuitGivealarmService {
    @Resource
    private SysDictMapper sysDictMapper;
    @Resource
    private SysDictItemMapper sysDictItemMapper;
    @Resource
    private DeviceMapper deviceMapper;
    @Resource
    private DeviceService deviceService;
    @Autowired
    private LinkappUserContextProducer linkappUserContextProducer;
    @Autowired
    private IRailGiveSystemAlarmService railGiveSystemAlarmService;
    @Autowired
    private SysDictItemService dictItemService;
    /**
     * 断路器报警故障保存
     */
    @Override
    public void datapushHandler(DatapushDTO datapushDTO){

        JSONObject data = datapushDTO.getData();

        Device device = datapushDTO.getDevice_data_latest();
        if (Objects.isNull(device)){
            return;
        }
        if (!DeviceConstant.RailwayDeviceType.CIRCUIT_BREAKER.getDescription().contains(device.getDeviceUnit().getDeviceTypeName())) {
            return;
        }
        //故障状态
        String fault_code = data.getString("fault_code");
        Double fault_value = data.getDouble("fault_value");
        String fault_description = data.getString("fault_description");

        Double a_phase_current = data.getDouble("a_phase_current");
        Double b_phase_current = data.getDouble("b_phase_current");
        Double c_phase_current = data.getDouble("c_phase_current");
        Double a_phase_voltage = data.getDouble("a_phase_voltage");
        Double b_phase_voltage = data.getDouble("b_phase_voltage");
        Double c_phase_voltage = data.getDouble("c_phase_voltage");
        Double a_phase_power = data.getDouble("a_phase_power");
        Double b_phase_power = data.getDouble("b_phase_power");
        Double c_phase_power = data.getDouble("c_phase_power");
        Double active_power = data.getDouble("active_power");
        Double residual_current = data.getDouble("residual_current");
        String line_online_state = data.getString("line_online_state");
        String switch_state = data.getString("switch_state");

        RailCircuitGivealarm giveAlarm  = new RailCircuitGivealarm();
        String  giveType = "";
        String  giveName = "";
        String  faultType = "";
            //
            device.setStatus(1);
            //设备编号
            String deviceCode = device.getCode();
            //租户id
            String tenantId = device.getTenantId();
            if (!StringUtils.isEmpty(fault_code)){
                //giveType 告警类型获取,判断是报警还是故障

                //判断是故障还是报警
                FaultCodeTypeEnum fault = FaultCodeTypeEnum.getEnumByCode(fault_code);
                if (!Objects.isNull(fault)){
                    giveType = "1";
                    giveName = fault.getName();
                }
                GiveCodeTypeEnum give = GiveCodeTypeEnum.getEnumByCode(fault_code);
                if (!Objects.isNull(give)){
                    giveType = "0";
                    giveName = give.getName();
                }
                if (StringUtils.isEmpty(giveType)){
                    return;
                }

                //获取报警,故障具体类型
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("dict_code_", "fault_type");
                SysDict sysDict = sysDictMapper.selectOne(queryWrapper);
                if (Objects.isNull(sysDict)){
                    return;
                }
                QueryWrapper itemQueryWrapper = new QueryWrapper();
                itemQueryWrapper.eq("dict_id_", sysDict.getId());
                itemQueryWrapper.eq("item_text_", giveName);
                SysDictItem sysDictItem = sysDictItemMapper.selectOne(itemQueryWrapper);
                if (Objects.isNull(sysDictItem)){
                    return;
                }
                faultType = sysDictItem.getItemValue();
                if (!Objects.isNull(fault_value)){
                    giveAlarm.setFaultValue(fault_value);
                }
                giveAlarm.setGiveType(giveType);
                giveAlarm.setFaultType(faultType);
                if (!Objects.isNull(fault_description)){
                    giveAlarm.setFaultDescription(fault_description);
                }
            }
            //保存
            giveAlarm.setDeviceCode(deviceCode);
            giveAlarm.setTenantId(tenantId);
            giveAlarm.setCode(fault_code);
            giveAlarm.setCreateTime(new Date());
            //总功率
            giveAlarm.setActivePower(active_power);
        giveAlarm.setResidualCurrent(residual_current);
        giveAlarm.setAPhaseCurrent(a_phase_current);
        giveAlarm.setAPhaseVoltage(a_phase_voltage);
        giveAlarm.setAPhasePower(a_phase_power);
        giveAlarm.setBPhaseCurrent(b_phase_current);
        giveAlarm.setBPhasePower(b_phase_power);
        giveAlarm.setBPhaseVoltage(b_phase_voltage);
        giveAlarm.setCPhaseCurrent(c_phase_current);
        giveAlarm.setCPhasePower(c_phase_power);
        giveAlarm.setCPhaseVoltage(c_phase_voltage);
        giveAlarm.setLineOnlineState(line_online_state);
        giveAlarm.setSwitchState(switch_state);
            save(giveAlarm);
            if (StringUtils.isNotEmpty(switch_state)){
                Device device1 = new Device();
                if (!Objects.isNull(device.getElectStatus())){
                    if (!String.valueOf(device.getElectStatus()).equals(switch_state)){
                        device1.setId(device.getId());
                        device1.setElectStatus("1".equals(switch_state)?0:"0".equals(switch_state)?1:0);
                        device1.setModifyTime(new Date());
                        deviceMapper.updateDeviceAreaById(device1);
                    }
                }else{
                    device1.setId(device.getId());
                    device1.setElectStatus("1".equals(switch_state)?0:"0".equals(switch_state)?1:0);
                    device1.setModifyTime(new Date());
                    deviceMapper.updateDeviceAreaById(device1);
                }
            }

            /**
             * 系统告警_锚点
             */
            if (StringUtils.isNotEmpty(giveAlarm.getFaultType()) && StringUtils.isNotEmpty(giveAlarm.getGiveType())){
                //断路器警告
                railGiveSystemAlarmService
                        .datapushHandlerUseEle(datapushDTO,dictItemService.selectByDictItem("testing_item","5"), RailGiveAlarmTypeConfigEnum.AlarmType_6);
            }

    }

    @Override
    public Map<String, Object> findTotalByPieChart() {
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();//*"9d8ec26eb12a86bf7b2924849a23b233";*///
        //通过租户id获取所有的断路器设备
        Map<String, Object> result = new HashMap<>();

        //所有断路器设备
        List<Device> deviceSiteInfos = deviceMapper.selectByDeviceTypeName(tenantId,DeviceConstant.RailwayDeviceType.CIRCUIT_BREAKER.getDescription());
        //List<Device> deviceSiteInfos = deviceMapper.selectDevices(device);
        //查询断路器报警故障记录
        int bjSum = baseMapper.countByTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId(), CircuitTypeEnum.CIRCUIT_TYPE_BJ.getValue());
        int gzSum = baseMapper.countByTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId(), CircuitTypeEnum.CIRCUIT_TYPE_GZ.getValue());
        int sum = bjSum + gzSum;
        List<String> permCodes = new ArrayList<>();
        Map<String, Map<String,Object>> transForMap = new HashMap<>();
        for (Device devicel:deviceSiteInfos){
            if (!StringUtils.isEmpty(devicel.getCode())){
                permCodes.add(devicel.getCode());
            }
            if (!transForMap.containsKey(devicel.getCode())){
                //设备放入统计map备用
                Map<String, Object> mpa_dev = new HashMap<>();
                mpa_dev.put("deviceName",devicel.getName());
                mpa_dev.put("deviceCode",devicel.getCode());
                mpa_dev.put("sum",0);
                transForMap.put(devicel.getCode(),mpa_dev);
            }
        }
        List<Map<String,Object>> resultPieArray = new ArrayList<>();
        //饼图
        //查询报警故障记录
        //List<Map<String,Object>> pieChart_arrs = new ArrayList<>();
        if(permCodes.size() !=0){
        QueryWrapper<RailCircuitGivealarm> objectQueryWrapper = new QueryWrapper<RailCircuitGivealarm>();
        objectQueryWrapper.in("device_code",permCodes);
        objectQueryWrapper.eq("tenant_id",tenantId);
        List<RailCircuitGivealarm> railCircuitGivealarms = baseMapper.selectList(objectQueryWrapper);
        for (RailCircuitGivealarm giveAlarm:railCircuitGivealarms){
            if (StringUtils.isNotEmpty(giveAlarm.getDeviceCode()) && StringUtils.isNotEmpty(giveAlarm.getGiveType())&& StringUtils.isNotEmpty(giveAlarm.getFaultType())){
                Map<String, Object> tmap = transForMap.get(giveAlarm.getDeviceCode());
                if (tmap!=null){
                    tmap.put("sum",Integer.valueOf(Objects.toString(tmap.get("sum"),"0"))+1);
                    transForMap.put(giveAlarm.getDeviceCode(),tmap);
                }
            }
        }
        }
        for (Map.Entry<String, Map<String,Object>> entry : transForMap.entrySet()) {
            Map<String, Object> value = entry.getValue();
            if (!Objects.isNull(value)){
                resultPieArray.add(value);
            }
        }
        result.put("bjSum",bjSum);
        result.put("gzSum",gzSum);
        result.put("sum",sum);
        result.put("pieChartArray",resultPieArray);
        return result;
    }

    @Override
    public Map<String, Object> faultTypeByColumnar(RailCircuitGivealarmDTO railCircuitGivealarmDTO) {
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        //获取设备作为查询条件
        List<String> permCodes = new ArrayList<>();
        if (StringUtils.isEmpty(railCircuitGivealarmDTO.getDeviceCode())) {
            List<Device> deviceSiteInfos = deviceMapper.selectByDeviceTypeName(tenantId, DeviceConstant.RailwayDeviceType.CIRCUIT_BREAKER.getDescription());
            for (Device devicel : deviceSiteInfos) {
                if (!StringUtils.isEmpty(devicel.getCode())) {
                    permCodes.add(devicel.getCode());
                }
            }
        }else{
            permCodes.add(railCircuitGivealarmDTO.getDeviceCode());
        }
        if (railCircuitGivealarmDTO.getCumulative().equals(0)){
            railCircuitGivealarmDTO.setStartDate(DateUtil.getLastDays(30));
            railCircuitGivealarmDTO.setEndDate(DateUtil.getYYYYMMDDDate(new Date()));
        }
        railCircuitGivealarmDTO.setDeviceCodes(permCodes);
        List<RailCircuitGivealarmVO> list = baseMapper.getList(railCircuitGivealarmDTO);
        //获取字典
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("dict_code_", "fault_type");
        SysDict sysDict = sysDictMapper.selectOne(queryWrapper);
        if (Objects.isNull(sysDict)){
            return null;
        }
        QueryWrapper<SysDictItem> itemQueryWrapper = new QueryWrapper();
        itemQueryWrapper.eq("dict_id_", sysDict.getId());
        List<SysDictItem> sysDictItems = sysDictItemMapper.selectList(itemQueryWrapper);
        List<String> abscissa = new ArrayList<>();
        List<String> abscissa_values = new ArrayList<>();
        List<Integer> giveAlarm = new ArrayList<>();
        List<Integer> giveFault = new ArrayList<>();
        for (SysDictItem dict:sysDictItems){
            abscissa.add(dict.getItemText());
            abscissa_values.add(dict.getItemValue());
            giveAlarm.add(0);
            giveFault.add(0);
        }
        Map<String, Object> result = new HashMap<>();
        for (RailCircuitGivealarmVO givealarmVo:list){
            int i = abscissa_values.indexOf(givealarmVo.getFaultType());
            if (!StringUtils.isEmpty(givealarmVo.getFaultType())  && i == -1){
                continue;
            }
            if (CircuitTypeEnum.CIRCUIT_TYPE_BJ.getValue().equals(givealarmVo.getGiveType())){
                Integer giveAlarm_v = giveAlarm.get(i);
                giveAlarm_v++;
                giveAlarm.add(i,giveAlarm_v);
            }else if(CircuitTypeEnum.CIRCUIT_TYPE_BJ.getValue().equals(givealarmVo.getGiveType())){
                Integer giveFault_v = giveFault.get(i);
                giveFault_v++;
                giveFault.add(i,giveFault_v);
            }
        }
        result.put("abscissa",abscissa);
        result.put("abscissaValues",abscissa_values);
        result.put("giveAlarm",giveAlarm);//报警
        result.put("giveFault",giveFault);//故障
        return result;
    }

    @Override
    public List<RailCircuitGivealarmVO> codeByNewRecords(String tenantId, List<String> value) {
        return baseMapper.codeByNewRecords(tenantId,value);
    }
}
